package com.ruoyi.develop.finance.financeAr.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsInvoiceDetail.domain.GoodsInvoiceDetail;
import com.ruoyi.develop.lvYifahuo.domain.LvYifahuo;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.finance.financeAr.mapper.FinanceArMapper;
import com.ruoyi.develop.finance.financeAr.domain.FinanceAr;
import com.ruoyi.develop.finance.financeAr.service.IFinanceArService;

/**
 * 应收账款Service业务层处理
 *
 * @author lmm
 * @date 2025-07-30
 */
@Service
public class
FinanceArServiceImpl implements IFinanceArService {
    @Resource
    private FinanceArMapper financeArMapper;
    @Autowired
    private ExportServiceImpl exportService;

    /**
     * 查询应收账款
     *
     * @param id 应收账款主键
     * @return 应收账款
     */
    @Override
    public FinanceAr selectById(String id) {
        return financeArMapper.selectById(id);
    }

    /**
     * 查询应收账款列表
     *
     * @param entity 应收账款
     * @return 应收账款
     */
    @Override
    public List<FinanceAr> selectList(FinanceAr entity) {
        return financeArMapper.selectList(entity);
    }

    @Override
    public void exportData(HttpServletRequest request, HttpServletResponse response, FinanceAr entity) {
        List<FinanceAr> list = financeArMapper.selectList(entity);
        for (FinanceAr financeAp : list) {
            Map<String, Object> params = new HashMap<>();
            params.put("occurDate", DateUtils.formatDate(financeAp.getOccurDate(), "yyyy-MM-dd"));
            params.put("sendDate", DateUtils.formatDate(financeAp.getSendDate(), "yyyy-MM-dd"));
            params.put("payReturnDate", DateUtils.formatDate(financeAp.getPayReturnDate(), "yyyy-MM-dd"));
            params.put("type", DictUtils.getDictLabel("ar_type", financeAp.getType()));
            financeAp.setParams(params);
        }
        String fileName = "客户应收列表.xlsx";
        String templateName = "客户应收列表导出模板.xlsx";
        Map<String, Object> params = new HashMap<>();
        params.put("list", list);
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

    /**
     * 新增应收账款
     *
     * @param entity 应收账款
     * @return 结果
     */
    @Override
    public int insert(FinanceAr entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        if(StringUtils.isBlank(entity.getNos())){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String today = sdf.format(entity.getOccurDate()==null?new Date():entity.getOccurDate());
            String codeMaxString = financeArMapper.selectMaxCode(today);
            if(StringUtils.isNotBlank(codeMaxString)){
                // 最大编号+1
                codeMaxString = Long.parseLong(codeMaxString)+1+"";
            }else{
                codeMaxString = today+"0001";
            }
            entity.setNos(codeMaxString);
        }

        try {
            entity.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            entity.setCreateBy("auto");
        }
        entity.setCreateTime(DateUtils.getNowDate());
        return financeArMapper.insert(entity);
    }

    /**
     * 修改应收账款
     *
     * @param entity 应收账款
     * @return 结果
     */
    @Override
    public int update(FinanceAr entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return financeArMapper.update(entity);
    }

    /**
     * 批量删除应收账款
     *
     * @param ids 需要删除的应收账款主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return financeArMapper.deleteByIds(ids);
    }

    /**
     * 删除应收账款信息
     *
     * @param id 应收账款主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return financeArMapper.deleteById(id);
    }

    @Override
    public void addBySend(LvYifahuo lvYifahuo) {
        // 应付 先查询该供应商有没有在应付列表里 如果有则查询最后一条数据，获取应付余额
        // 如果没有则新增一条数据
        FinanceAr financeArLastOne = financeArMapper.selectLastOneByCustomerId(lvYifahuo.getKehuId());
        BigDecimal remainMoney = BigDecimal.ZERO;
        if (financeArLastOne != null) {
            remainMoney = financeArLastOne.getRemainMoney();
        }
        FinanceAr financeAr = new FinanceAr();
        financeAr.setOccurDate(DateUtils.getNowDate());
        financeAr.setCustomerId(lvYifahuo.getKehuId());
        financeAr.setCustomerName(lvYifahuo.getKehuName());
        financeAr.setSendId(lvYifahuo.getId());
        financeAr.setSendNos(lvYifahuo.getNos());
        financeAr.setSendDate(lvYifahuo.getFahuoDate());
        financeAr.setType(BusinessConstants.AR_TYPE_SEND);
        financeAr.setDeliveryMoney(lvYifahuo.getTaxAllmoeny());
        financeAr.setRemainMoney(remainMoney.add(lvYifahuo.getTaxAllmoeny()));
        this.insert(financeAr);
    }


    /**
     * 发票核销 回款
     */
    @Override
    public void addByBackMoney(GoodsInvoiceDetail invoiceDetail) {
        // 应付 先查询该供应商有没有在应付列表里 如果有则查询最后一条数据，获取应付余额
        // 如果没有则新增一条数据
        FinanceAr financeArLastOne = financeArMapper.selectLastOneByCustomerId(invoiceDetail.getCustomerId());
        BigDecimal remainMoney = BigDecimal.ZERO;
        if (financeArLastOne != null) {
            remainMoney = financeArLastOne.getRemainMoney();
        }
        FinanceAr financeAr = new FinanceAr();
        financeAr.setOccurDate(DateUtils.getNowDate());
        financeAr.setCustomerId(invoiceDetail.getCustomerId());
        financeAr.setCustomerName(invoiceDetail.getCustomerName());
        financeAr.setPayReturnId(invoiceDetail.getId());
        financeAr.setPayReturnDate(invoiceDetail.getPinDate());
        financeAr.setPayReturnNos(invoiceDetail.getNos());
        financeAr.setType(BusinessConstants.AR_TYPE_RECEIVE_PAYMENT);
        financeAr.setAcceptMoney(invoiceDetail.getPinMoney());
        financeAr.setRemainMoney(remainMoney.subtract(invoiceDetail.getPinMoney()));
        this.insert(financeAr);
    }


    /**
     * 发票撤销回款
     */
    @Override
    public void addByBackMoneyCancel(GoodsInvoiceDetail invoiceDetail) {
        // 应付 先查询该供应商有没有在应付列表里 如果有则查询最后一条数据，获取应付余额
        // 如果没有则新增一条数据
        FinanceAr financeArLastOne = financeArMapper.selectLastOneByCustomerId(invoiceDetail.getCustomerId());
        BigDecimal remainMoney = BigDecimal.ZERO;
        if (financeArLastOne != null) {
            remainMoney = financeArLastOne.getRemainMoney();
        }
        FinanceAr financeAr = new FinanceAr();
        financeAr.setOccurDate(DateUtils.getNowDate());
        financeAr.setCustomerId(invoiceDetail.getCustomerId());
        financeAr.setCustomerName(invoiceDetail.getCustomerName());
        financeAr.setPayReturnId(invoiceDetail.getId());
        financeAr.setPayReturnDate(invoiceDetail.getPinDate());
        financeAr.setPayReturnNos(invoiceDetail.getNos());
        financeAr.setType(BusinessConstants.AR_TYPE_RECEIVE_PAYMENT_CANCEL);
        financeAr.setAcceptMoney(invoiceDetail.getPinMoney().negate());
        financeAr.setRemainMoney(remainMoney.add(invoiceDetail.getPinMoney()));
        this.insert(financeAr);
    }










}
